package com.wsapi.core.service.impl;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.stereotype.Service;

import com.wsapi.core.dao.AccountDao;
import com.wsapi.core.dao.model.SysAccount;
import com.wsapi.core.dao.model.SysRole;
import com.wsapi.core.dao.model.SysRolePerm;
import com.wsapi.core.service.AccountService;

/**
 * Created with IntelliJ IDEA. User: yangyan Date: 13-11-19 Time: 下午8:35
 */
@Service
public class AccountServiceImpl implements AccountService {

    @Resource
    private AccountDao accountDao;

    @Override
    public String checkLogin(String userName, String password) {
        String hql = "from SysAccount as acc where acc.accName = ?";
        SysAccount acc = (SysAccount) accountDao.getCurrentSession()
                .createQuery(hql).setParameter(0, userName).uniqueResult();

        if (acc == null) {
            throw new UnknownAccountException();
        }

        if (acc != null && password.equals(acc.getAccPassword())) {
            return String.valueOf(acc.getAccId());
        } else{
          throw new IncorrectCredentialsException();
        }
    }

    @Override
    public Set<String> getAccountPermissions(String accId) {
        Set<SysRole> roles = this.getAccountRoles(accId);
        Set<String> permissions = new HashSet<String>();
        if (roles != null) {
            for (SysRole role : roles) {
                Set<SysRolePerm> permissions2 = role.getPermissions();
                if (permissions2 != null) {
                    for (SysRolePerm sysRolePerm : permissions2) {
                        permissions.add(sysRolePerm.getPermKey());
                    }
                }
            }
        }
        return permissions;
    }

    @Override
    public Set<SysRole> getAccountRoles(String accId) {
        SysAccount account = this.accountDao.getById(Integer.valueOf(accId));
        return account.getRoles();
    }
}
